"""
题目：统计“三国演义.TXT”中出现频率最高的前5位人物。文件名：san.py。
"""
import jieba


"""判断一个unicode是否是汉字"""
def is_chinese(uchar):
    if uchar >= u'\u4e00' and uchar <= u'\u9fa5':
        return True
    else:
        return False

excludes = {"将军","却说","荆州","二人","不可","不能","如此","大喜","商议","如何","军士","左右","军马","次日","引兵"}
name_group =[["刘备","玄德曰","玄德","刘皇叔","刘使君"],["孔明","诸葛亮"],["曹操","丞相"],["关羽","关公"]]
f = open("三国演义.txt", "r", encoding="utf-8")
all_str = f.read();
ans_cnt = {}
# words = jieba.lcut(all_str)
words  = jieba.cut(all_str,cut_all = False)
# 得到词语频数
for i in words:
    if not is_chinese(i):
        continue
    elif len(i) == 1:
        continue
    else:
        ans_cnt[i] = ans_cnt.get(i,0)+1
# 去除不需要的
for i in excludes:
    del ans_cnt[i]
# 合并同一个人不同名字
for names in name_group:
    for j in range(1,len(names)):
        ans_cnt[names[0]] += ans_cnt[names[j]]
        ans_cnt.pop(names[j])

# 排序
ans_cnt_sort = sorted(ans_cnt.items(),key=lambda x:x[1],reverse=True)
# 打印前20个
for i in range(0,20):
    print(ans_cnt_sort[i])
